
import { observable, configure } from "mobx";
import get from "lodash/get";
import templateApi from "@/api/templateApi";
import utils from "src/utils";

configure({ enforceActions: "never" });

const templateStore = observable({
    // 是否显示弹窗
    visible: false,
    setVisible(visible) {
        this.visible = visible;
    },

    // 模板分组
    cascaderOptions: [],
    async getTemplateGroup() {
        const result = (await templateApi.get_template_group().catch(() => []));
        const cascaderOptions = result.map((group) => ({
            value: group.id,
            text: group.name,
            children: (group.sonList || []).map((child) => ({
                value: child.id,
                text: child.name,
            })),
        }));

        this.cascaderOptions = cascaderOptions;
        this.setActiveid([
            get(cascaderOptions, [0, "value"]),
            get(cascaderOptions, [0, "children", 0, "value"]),
        ]);
    },

    // 当前选中的分组
    activeid: [0, 0],
    async setActiveid(activeid) {
        this.activeid = activeid;
        this.page = 1;
        this.hasNext = true;
        this.templates = [];
        this.loading = true;
        await new Promise(resolve => setTimeout(resolve, 100));
        this.getTemplates();
    },

    // 加载中
    loading: false,
    setLoading(loading) {
        if (loading) {
            this.loading = loading;
        } else {
            setTimeout(() => {
                this.loading = loading;
            }, 300);
        }
    },

    page: 1,
    pageSize: 10,
    hasNext: true,

    // 搜索词
    searchValue: "",
    setSearchValue(searchValue) {
        this.page = 1;
        this.templates = [];
        this.searchValue = searchValue;
        this.hasNext = true;
        this.getTemplates();
    },

    // 模板列表
    templates: [],
    async getTemplates() {
        this.setLoading(true);
        const { page, pageSize, searchValue, activeid } = this;
        const { list, totalCount } = await templateApi
            .get_templates({ groupId1: activeid[1], pageNo: page, pageSize, searchValue })
            .catch(() => ({ list: [], totalCount: 0 }));
        list.map((l, i) => {
            l.designData = utilsONParse(l.designData);
        });
        this.templates.push(...list);
        this.hasNext = list.length === this.pageSize;
        this.setLoading(false);
    },
    getNextPage() {
        if (this.loading || !this.hasNext) {
            return;
        }
        this.page += 1;
        this.getTemplates();
    },
});

// 初始化获取模板分组
templateStore.getTemplateGroup();

export default templateStore;
